package com.cndongtai.controller.firmware;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cndongtai.constant.SystemConstant;
import com.cndongtai.constant.UserConstant;
import com.cndongtai.controller.BaseController;
import com.cndongtai.po.Firmware;
import com.cndongtai.po.Light;
import com.cndongtai.po.LightFirmware;
import com.cndongtai.po.User;
import com.cndongtai.service.firmware.FirmwareService;
import com.cndongtai.service.firmware.LightFirmwareService;
import com.cndongtai.service.light.LightService;
import com.cndongtai.service.net.NetService;
import com.cndongtai.util.ByteUtil;
import com.cndongtai.util.DESUtil;
import com.cndongtai.util.ValidateUtil;
import com.cndongtai.vo.FirmwareBean;
import com.cndongtai.vo.LightFirmwareBean;

@Controller
public class LightFirmwareController extends BaseController {
	
	@Resource(name="netService")
	private NetService netService;
	
	@Resource(name="firmwareService")
	private FirmwareService firmwareService;
	
	@Resource(name="lightFirmwareService")
	private LightFirmwareService lightFirmwareService;
	
	@Resource(name="lightService")
	private LightService lightService;
	
	@RequestMapping("/lightFirmwareMgr")
	public String lightFirmwareMgr() {
		User loginUser = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		
		// 展示设备列表    操作：一键升级  升级记录  与firmware表做关联，判断是否存在升级
		if(loginUser!=null && "admin".equals(loginUser.getUsername())) {
			List<LightFirmwareBean> lightFirmwareList = lightFirmwareService.queryLightFirmwareList(null);
			request.setAttribute("lightFirmwareList", lightFirmwareList);
			
			List<FirmwareBean> firmwareList = firmwareService.queryFirmwareList();
			request.setAttribute("firmwareList", firmwareList);
		}
		
		return "/firmware/lightFirmwareMgr";
	}
	
	@RequestMapping("/upFirmware")
	@ResponseBody
	public void upFirmware() {
		JSONObject result = new JSONObject();
		User loginUser = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		if(loginUser==null || !"admin".equals(loginUser.getUsername())) {
			result.put("success", "-1");
			result.put("msg", "权限不够");
			this.writeData(result);
			return;
		}
		
		String panId = this.getValue("panId");
		String lightNum = this.getValue("lightNum");
		String uploadType = "22";//目前只能升级控制模块
		String firmwareId = this.getValue("firmwareId");
		
		if(ValidateUtil.empty(panId)) {
			result.put("success", "-1");
			result.put("msg", "panId不能为空");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(lightNum)) {
			result.put("success", "-1");
			result.put("msg", "lightNum不能为空");
			this.writeData(result);
			return;
		}
		
		Long id = null;
		try {
			id = Long.parseLong(firmwareId);
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		if(id==null) {
			result.put("success", "-1");
			result.put("msg", "固件不存在");
			this.writeData(result);
			return;
		}
		
		// 校验设备是否存在
		Light light = lightService.queryLightByLightNumAndPanId(panId, lightNum);
		if(light==null) {
			result.put("success", "-1");
			result.put("msg", "设备不存在");
			this.writeData(result);
			return;
		}
		
		// 读取设备信息
		LightFirmware lightFirmware = netService.readDeviceFirmwareInfo(panId, lightNum, uploadType);
		if(lightFirmware==null) {
			result.put("success", "-1");
			result.put("msg", "读取设备硬件信息失败，无法进行升级");
			this.writeData(result);
			return; 
		}
		
		lightFirmware.setLightId(light.getLightId());
		lightFirmware.setLastUptTime(new Date());
		
		lightFirmwareService.addOrUpdateLightFirmware(lightFirmware);
		
		
		// 获取固件信息
		// String url,Integer firmwareSize,Integer firmwareCRC, Integer timeOut
		Firmware firmware = firmwareService.queryFirmwareById(id);
		if(firmware==null) {
			result.put("success", "-1");
			result.put("msg", "固件不存在");
			this.writeData(result);
			return;
		}
		
		// 加密id
		String version = "";
		try {
			version = DESUtil.defaultEncrypt(id+"");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			result.put("success", "-1");
			result.put("msg", "网络故障，请稍后重试");
			this.writeData(result);
			return;
		}
		
		String url = "http://www.365ctrl.com/downloadFirmware.do?version=" + version;
		
		int firmwareSize = 0;
		int firmwareCRC = 0;
		
		// 读取文件
		File file = new File(SystemConstant.FILE_FIRMWARE_PATH+firmware.getUrl());
		if(file.exists()) {
			FileInputStream in = null;
			try {
				in = new FileInputStream(file);
				byte[] content = new byte[10240];
				firmwareSize = in.read(content);
				firmwareCRC = ByteUtil.cal_crc(content, firmwareSize);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				if(in != null) {
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		}else {
			result.put("success", "-1");
			result.put("msg", "固件不存在");
			this.writeData(result);
			return;
		}
		
		// 添加升级记录
		
		// 进行升级
		
		String returncode = netService.upFirmware(panId, lightNum, uploadType, firmware.getProtocalVersion(), firmware.getHardwareVersion(), firmware.getFirmwareVersion(), url, firmwareSize, firmwareCRC);
		
		
		
		
		result.put("success", "0");
		result.put("msg", returncode);
		this.writeData(result);
	}
	
}
